<template>
  <view class="flex-col">

    <view :class="boole?'bottom115':''">
      <!--基础信息-->
      <basic-info v-model="detailForm"/>

      <!--我司购买  投保要求-->
      <view class="item-wrap" v-if="Number(detailForm.insuranceChannels) === 1">

        <division-purchase v-model="detailForm" :insuranceList="insuranceList" :boole="boole"
                           ref="refDivisionPurchase"/>

        <view style="margin: 8rpx 20rpx 30rpx 20rpx">
          <uni-forms ref="detailForm" :model="detailForm" :label-position="boole ? 'top' : 'left'" labelWidth="auto">

            <view style="margin-bottom:20rpx">
              <text>保险套餐</text>
            </view>

            <uni-table ref="table" border stripe emptyText="暂无更多数据">
              <uni-tr>
                <uni-th width="70" align="center" v-if="detailForm.addProStatus == 1 && boole">操作</uni-th>
                <uni-th width="130" align="center">商业险种</uni-th>
                <uni-th width="120" align="center">保额/万元</uni-th>
              </uni-tr>
              <uni-tr v-for="(item, index) in detailForm.businessList" :key="index">
                <uni-td v-if="detailForm.addProStatus == 1 && boole" align="center"
                        style="display: flex;align-items: center;width: fit-content">
                  <view style="display: flex;justify-content: center;align-items: center;height: 100%">
                    <button class="uni-button del-but" size="mini" @click="handleDle( index )" type="warn">删除
                    </button>
                  </view>

                </uni-td>

                <uni-td align="center">
                  <text>{{ item.insuranceProName }}</text>
                </uni-td>

                <uni-td align="center">
                  <view v-if="boole">
                    <uni-easyinput v-if="detailForm.addProStatus == 1" v-model="item.insuranceQuota"/>
                    <text v-if="detailForm.addProStatus == 2">{{ item.insuranceQuota }}</text>
                  </view>
                  <text v-else>{{ item.insuranceQuota }}</text>
                </uni-td>

              </uni-tr>
            </uni-table>

            <view style="display: flex;justify-content: space-between;align-items: center;margin-top:20rpx"
                  v-if="Number(detailForm.addProStatus) === 1 &&
                  detailForm.businessList.length !== dict.type.insurance_project.length && boole">
              <button class="uni-button add-button" v-if="insuranceProName !== ''" size="mini" type="primary"
                      @click="addDecoration">
                添加
              </button>
              <zxz-uni-data-select v-model="insuranceProValue" @change="handleProValue" class="add-uni-data"
                                   :localdata="dict.type.insurance_project" dataKey="label" dataValue="value"
                                   placeholder="请选择商业险种"
                                   ref="refZxzUniDataSelect"
                                   :clear="true" :filterable="false"/>
            </view>
          </uni-forms>
        </view>
      </view>

      <!--交强险信息-->
      <jqx-info v-model="detailForm" :boole="boole" v-if="Number(detailForm.insuranceChannels) !== 1" :options="options"
                :insuranceList="insuranceList"
                ref="refJqxInfo"/>

      <view class="item-wrap" v-if="Number(detailForm.insuranceChannels) !== 1">
        <!--商业险信息-->
        <syx-info v-model="detailForm" :boole="boole" :insuranceList="insuranceList" :options="options"
                  ref="refSyxInfo"/>

        <!--商业险信息 保险套餐-->
        <view style="margin: 8rpx 20rpx 30rpx 20rpx">

          <uni-forms ref="detailForm" :model="detailForm" :label-position="boole ? 'top' : 'left'" labelWidth="auto">

            <view style="margin-bottom:20rpx">
              <text>保险套餐</text>
            </view>

            <uni-table ref="table" border stripe emptyText="暂无更多数据">
              <uni-tr>
                <uni-th width="70" align="center" v-if="Number(detailForm.insuranceChannels) === 3 && boole">操作
                </uni-th>
                <uni-th width="130" align="center">商业险种</uni-th>
                <uni-th width="120" align="center">保额/万元</uni-th>
                <uni-th width="130" align="center">保险费用/元</uni-th>
              </uni-tr>
              <uni-tr v-for="(item, index) in detailForm.businessList" :key="index">

                <uni-td align="center" v-if="Number(detailForm.insuranceChannels) === 3 && boole">
                  <view style="display: flex;justify-content: center;align-items: center;height: 100%">
                    <button class="uni-button del-but" size="mini" v-if="item.boole" @click="handleDle( index )"
                            type="warn">删除
                    </button>
                  </view>
                </uni-td>

                <uni-td align="center">
                  <text>{{ item.insuranceProName }}</text>
                </uni-td>

                <uni-td align="center">
                  <uni-easyinput v-if="boole && Number(detailForm.insuranceChannels) === 3"
                                 v-model="item.insuranceQuota"/>
                  <text v-else>{{ item.insuranceQuota }}</text>
                </uni-td>

                <uni-td align="center">
                  <uni-forms-item :name="'businessList.'+index+'.insurancePrice'"
                                  :rules="[{ required:boole, errorMessage: '请输入保险费用/元', validateTrigger: 'blur'}]">
                    <uni-easyinput v-if="boole" v-model="item.insurancePrice"
                                   @clear="clear(item,'insurancePrice')"
                                   @blur="blurTable(item,'insurancePrice')"/>
                    <text v-else>{{ item.insurancePrice }}</text>
                  </uni-forms-item>
                </uni-td>

              </uni-tr>
            </uni-table>

            <view style="display: flex;justify-content: space-between;align-items: center;margin-top:20rpx"
                  v-if="Number(detailForm.insuranceChannels)  === 3 &&  detailForm.businessList.length !== dict.type.insurance_project.length && boole">
              <button class="uni-button add-button" v-if="insuranceProName !== ''" size="mini" type="primary"
                      @click="addDecoration">
                添加
              </button>
              <zxz-uni-data-select v-model="insuranceProValue" @change="handleProValue" class="add-uni-data"
                                   :localdata="dict.type.insurance_project" dataKey="label" dataValue="value"
                                   placeholder="请选择商业险种"
                                   ref="refZxzUniDataSelect"
                                   :clear="true" :filterable="false"/>
            </view>

            <uni-forms-item label="商业险保单:" name="syxPolicyUrl" :required="boole"
                            :rules="[{required:true,errorMessage:'上传商业险保单',validateTrigger: 'blur'}]"
                            v-if="detailForm.insuranceVoList.length === 1 && Number(detailForm.insuranceChannels) === 3">
              <text class="syxPolicyUrl "/>
              <image-common :disabled="!boole" :up-type="2" v-model="detailForm.syxPolicyUrl"/>
            </uni-forms-item>

          </uni-forms>
        </view>
      </view>

      <!-- 非车保险 -->
      <other v-model="detailForm" :boole="boole"/>

      <!-- 合计费用-->
      <total-expense v-model="detailForm" :type="1" v-if="[2,3].includes(Number(detailForm.insuranceChannels))"/>

      <!-- 备注 -->
      <remark v-model="detailForm" :boole="boole" v-if="Number(detailForm.insuranceChannels) !== 1" ref="refRemark"/>

      <!--审批流程-->
      <exam-flow v-if="flowId" :instanceId="flowId"/>
    </view>

    <view class="button-container" v-if="boole">
      <button class="btn-item" @click="submit">提 交</button>
    </view>

  </view>
</template>

<script>
import {
  batchData,
  getWorkDetails,
  newAddInsuranceList,
} from "@/api/newCarInsure";
import {getInsuranceSelectList} from "@/api/maintain/maintainList";
import basicInfo from "./components/basicInfo.vue";
import divisionPurchase from "./components/divisionPurchase.vue";
import jqxInfo from "./components/jqxInfo.vue";
import syxInfo from "./components/syxInfo.vue";
import other from "./components/other.vue";
import totalExpense from "./components/totalExpense.vue"
import remark from "./components/remark.vue";

export default {
  name: "add",
  dicts: ["insurance_channels", "insurance_project"],
  components: {basicInfo, divisionPurchase, jqxInfo, syxInfo, other,totalExpense, remark},
  computed: {
    insuranceList() {
      return this.dict.type.insurance_channels
    },
    handleLabel() {
      return function (arr, type) {
        let name = "";
        arr.map((v) => {
          if (type == v.value) {
            name = v.label;
          }
        });
        return name;
      };
    },
  },
  watch: {
    "detailForm.syxPolicyUrl": {
      handler(val) {
        if (val) {
          this.$refs.detailForm.clearValidate(["syxPolicyUrl"]);
        }
      },
      deep: true,
    },
  },
  data() {
    return {
      insuranceProName: "",
      insuranceProValue: "",
      range: [
        {value: "1", text: "运营"},
        {value: "2", text: "非运营"},
      ],
      boole: false,
      flowId: null,
      options: [],
      // 表单参数
      detailForm: {
        //基础信息
        carCount: "",
        brandName: "",
        carId: "",
        carNo: "",
        contractReportNumber: "",
        decorateProList: "",
        guidancePrice: "",
        insuranceChannels: "",
        modelName: "",
        operationsName: "",
        procurementReportNumber: "",
        propertyRightName: "",
        purchasePrice: "",
        rentInsuranceCompany: "",
        seriesName: "",
        surplusTotalPrice: "",
        totalPrice: "",
        vinNo: "",
        workId: "",

        //交强险信息
        jqxCompany: "",
        jqxPolicyCode: "",
        jqxCompanyCode: "",
        jqxCompanyId: "",
        jqxExpectBeginTime: "",
        jqxExpectEndTime: "",
        jqxInsuranceType: "",
        jqxAmount: "",
        carTaxStatus: 1,
        carTax: "",
        jqxPolicyUrl: "",
        jqxInsuredName: "",

        //商业险信息
        syxCompany: "",
        syxCompanyId: "",
        syxPolicyCode: "",
        syxCompanyCode: "",
        syxExpectBeginTime: "",
        syxExpectEndTime: "",
        syxInsuranceType: "1",
        syxAmount: "",
        businessList: [],
        insuranceVoList: [],
        syxPolicyUrl: "",
        syxInsuredName: "",
        otherOpenStatus: 0,
        workIdList: [],
        attachmentUrl: "",
        dbFirstPolicyUrl: "",
        addProStatus: 1,
      },
    };
  },

  onLoad(op) {
    let title = "";
    this.flowId = op?.flowId;
    this.detailForm.carId = op?.carId;
    this.detailForm.workId = op?.id;
    title = `新增保险询价单(${op?.insuranceChannels === '1' ? '我司购买' :
        op?.insuranceChannels === '2' ? '店端投保' : op?.insuranceChannels === '3' ? '客户自购' : ''})`;
    if (op?.type === "edit") {
      this.boole = true;
    }

    if (op?.type === "view") {
      this.boole = false;
      title = '保险询价单详情'
    }

    this.handleData(op);

    this.detailForm.carId = op?.carId;
    uni.setNavigationBarTitle({
      title,
    });
  },

  mounted() {
    this.handleList();
  },

  methods: {
    // 获取详情
    async handleData(op) {
      let id = op?.businessDataId || null;
      let workOrderStatus = Number(op.workOrderStatus);
      let type = op.type;
      let data = {};

      try {
        if (workOrderStatus === 1) {
          // 处理详情
          let res = await batchData([op.id]);
          data = res.data;
        }

        if (id && (workOrderStatus === 5 || type === "view")) {
          // 详情总览
          let resD = await getWorkDetails(id);
          data = resD.data;
        }


        this.detailForm = {
          ...data,
          otherOpenStatus: data?.otherOpenStatus || 0,
          jqxInsuredName: data?.jqxInsuredName || op.propertyRightName || "",
          syxInsuredName: data?.syxInsuredName || op.propertyRightName || "",
        };
        this.detailForm.workId = op.id
        console.log(this.detailForm)
      } catch (e) {
        console.error(e);
      }
    },

    //新增保险套餐
    addDecoration() {
      let obj = {
        createBy: null,
        createTime: null,
        delFlag: null,
        id: null,
        insuranceId: null,
        insuranceManageId: null,
        insurancePrice: null,
        insuranceProCode: Number(this.insuranceProValue),
        insuranceProName: this.insuranceProName,
        insuranceQuota: "",
        updateBy: null,
        updateStatus: null,
        updateTime: "",
        boole: true,
      };
      this.detailForm.businessList.push(obj);
      this.insuranceProName = "";
      this.insuranceProValue = "";
      this.$forceUpdate();
    },

    //获取保险公司
    handleList() {
      getInsuranceSelectList({businessTypeCode: "5"}).then((res) => {
        if (res.code === 200) {
          this.options = res.data;
        }
      });
    },

    handleDle(index) {
      this.detailForm.businessList.splice(index, 1);
    },

    handleProValue(val) {
      if (val) {
        const findResult = this.detailForm.businessList.find(a =>
            Number(a.insuranceProCode) === Number(val.value)
        );

        if (findResult) {
          this.$modal.msgError('商业险种已有,请重新选择');
          this.$refs.refZxzUniDataSelect.clearVal()
          return;
        }

        this.insuranceProValue = val.value;
        this.insuranceProName = val.label;
      }
    },

    async submit() {
      try {
        let effectPromises = [
          this.$refs.refDivisionPurchase?.handleEffect(),
          this.$refs.refJqxInfo?.handleEffect(),
          this.$refs.refSyxInfo?.handleEffect(),
          this.$refs.refRemark?.handleEffect(),
          this.handleEffect(),
        ];
        await Promise.all(effectPromises);
        uni.showLoading();
        const res = await newAddInsuranceList(this.detailForm);
        if (res.code === 200) {
          uni.$emit("refBackList", true);
          this.$modal.msgSuccess("提交成功");
          setTimeout(() => {
            this.$tab.navigateBack();
          }, 1000);
        }
      } catch (error) {
        if (typeof error === "string") {
          this.$nextTick(() => {
            uni.pageScrollTo({
              selector: error,
            });
          });
        } else {
          console.error(error);
        }
      } finally {
        setTimeout(() => {
          uni.hideLoading();
        }, 1000)
      }
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm
            .validate()
            .then((res) => {
              resolve();
            })
            .catch((err) => {
              let key = ".flex-col" + ">>>" + "." + err[0].key;
              reject(key);
            });
      });
    },

    blurTable(row, field) {
      if (row[field]) {
        const reg = /^(?:[1-9]\d*|0)(?:\.\d{0,2})?$/;
        const match = row[field].toString().match(reg);
        row[field] = match ? match[0] : "";
      }
      if ([2, 3].includes(Number(this.detailForm.insuranceChannels)) && field === 'insurancePrice') {
        this.detailForm.syxAmount = this.handleCount()
      }
    },

    handleCount() {
      let num = 0;
      this.detailForm.syxAmount = 0;

      for (let i = 0; i < this.detailForm.businessList.length; i++) {
        num += Math.round(Number(this.detailForm.businessList[i].insurancePrice) * 100);
      }
      return (num / 100).toFixed(2);
    },

    clear(row, field) {
      row[field] = ''
    }
  },
};
</script>

<style lang="scss" scoped>
.add-button {
  margin-right: 20rpx;
}

.add-uni-data {
  flex: 1;
}

.del-but {
  padding-right: 20rpx;
  padding-left: 20rpx;
}
</style>


